package com.example.lightenergypolymerize.controller;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.lightenergypolymerize.entity.Answer;
import com.example.lightenergypolymerize.entity.enums.AiModelEnum;
import com.example.lightenergypolymerize.entity.enums.AiTypeEnum;
import com.example.lightenergypolymerize.service.IAnswerService;
import com.example.lightenergypolymerize.util.AppVariable;
import com.example.lightenergypolymerize.util.ResponseEntity;
import com.example.lightenergypolymerize.util.SecurityUtil;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/qianfan")
public class QianFanController {
    @Value("${baidu.app-key}")
    private String apiKey;
    @Value("${baidu.secret-key}")
    private String secretKey;
    @Resource
    IAnswerService answerService;
    @Resource
    private RedissonClient redissonClient;
    @RequestMapping("/chat")
    public ResponseEntity chat(String question){
        if(!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("请先输入内容");
        }

        String result = "";//大模型返回的结果
        boolean addResult = false;//数据是否添加到了数据库
        //执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.OPENAI.getValue(), AiTypeEnum.CHAT.getValue());
        //1.获取分布式锁示例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            //2.获取分布式锁
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                //获取分布式锁失败
                return ResponseEntity.fail("请勿频繁调用接口");
            }

            ChatResponse response = new Qianfan(apiKey, secretKey).chatCompletion()
                    .model("Yi-34B-Chat") // 使用model指定预置模型
                    .addMessage("user", question) // 添加用户消息 (此方法可以调用多次，以实现多轮对话的消息传递)
                    .execute(); // 发起请求
            result = response.getResult();
            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(result);
            answer.setModel(AiModelEnum.QIANFAN.getValue());
            answer.setUid(SecurityUtil.getCurrentUser().getUid());
            answer.setType(AiTypeEnum.CHAT.getValue());
            addResult = answerService.save(answer);
        }catch (Exception e) {

        }finally {
            //3.释放分布式锁
            rLock.unlock();
        }
        if(addResult) {
            return ResponseEntity.succ(result);
        }
        return ResponseEntity.fail("操作失败");
    }


    /**
     * 获取历史对话信息
     */
    @RequestMapping("/getchatlist")
    public ResponseEntity getChatList() {
        QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("model", AiModelEnum.QIANFAN.getValue());
        queryWrapper.eq("type", AiTypeEnum.CHAT.getValue());
        queryWrapper.eq("uid", SecurityUtil.getCurrentUser().getUid());
        queryWrapper.orderByDesc("aid");
        return ResponseEntity.succ(answerService.list(queryWrapper));
    }


}
